package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.auth.constant.PhoneCode;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.service.SmsService;
import com.atguigu.gulimall.common.vo.MemberVo;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import com.atguigu.gulimall.common.exception.BizCodeEnum;
import com.atguigu.gulimall.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;


@Controller
public class AuthController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SmsService smsService;

    @Autowired
    private MemberFeignService memberFeignService;

    // 本来需要在third-party服务调用短信接口
    @ResponseBody
    @GetMapping("/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        // 验证码防刷
        boolean b = smsService.sendCode(phone);
        if (!b) {
            return R.error(BizCodeEnum.SMS_CODE_REPEAT.getCode(), BizCodeEnum.SMS_CODE_REPEAT.getMessage());
        }
        return R.ok();
    }


    // 注意：如果返回的是 forward:/reg.html 会出错，forward:/reg.html 默认是get请求，但是是转发，相当于post请求get路径
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result) {
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            System.out.println("错误消息如下");
            fieldErrors.forEach(item -> {
                System.out.println(item.getDefaultMessage());
            });
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 判断 code 是否错误
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(PhoneCode.SMS_PHONE_PREFIX + vo.getPhone());
        if (StringUtils.isNotEmpty(s)) {
            String[] split = s.split("_");
            if (!split[0].equals(code)) {
                return "redirect:http://auth.gulimall.com/reg.html";
            }
            // 删除验证码
            redisTemplate.delete(PhoneCode.SMS_PHONE_PREFIX + vo.getPhone());
            // 远程调用member服务
            R r = memberFeignService.regist(vo);
            Integer status = (Integer) r.get("code");
            if (status == 0) {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }
        return "redirect:http://auth.gulimall.com/reg.html";
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, HttpSession session) {
        R r = memberFeignService.login(vo);
        System.out.println("响应码： " + r.get("code"));
        Integer code = (Integer) r.get("code");
        if (code == 0) {
            // 1. 使用 SpringSession 解决session共享问题
            // 2. 解决不同域名session共享问题
            String username =(String) r.get("username");
            System.out.println("username -> "+username);
            session.setAttribute("username",username);
//            保存用户
            System.out.println("r:"+r);
            MemberVo loginUser = (MemberVo) r.getData("userLogin",new TypeReference<MemberVo>(){});
            System.out.println("loginUser:"+loginUser);
            System.out.println("loginUser:"+loginUser);
            session.setAttribute("loginUser",loginUser);
            return "redirect:http://gulimall.com";
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
